package com.gitee.wsl.android.net.security.token

import android.content.Context
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStoreFile
import com.gitee.wsl.jvm.net.security.token.AuthenticationData
import com.gitee.wsl.jvm.net.security.token.TokenStorage
import java.time.Instant
import kotlinx.coroutines.flow.first


class TokenStorageImpl constructor (context: Context) : TokenStorage {
    private val datastore = PreferenceDataStoreFactory.create { context.preferencesDataStoreFile(
        TOKEN_STORAGE_FILE_NAME
    ) }

    override suspend fun updateAuthData(authData: AuthenticationData) {
        datastore.edit { prefs ->
            prefs[expirationKey] = authData.expiration.toEpochMilli()
            prefs[authTokenTypeKey] = authData.tokenType
            prefs[authTokenKey] = authData.token
        }
    }

    override suspend fun getAuthData(): AuthenticationData? {
        val expiration = datastore.data.first()[expirationKey]
        val tokenType = datastore.data.first()[authTokenTypeKey]
        val token = datastore.data.first()[authTokenKey]
        return if (expiration != null && tokenType != null && token != null) {
            AuthenticationData(tokenType, Instant.ofEpochMilli(expiration), token)
        } else {
            null
        }
    }

    companion object {
        private const val TOKEN_STORAGE_FILE_NAME = "TokenManager"
        val authTokenKey = stringPreferencesKey("AUTH_TOKEN")
        val expirationKey = longPreferencesKey("AUTH_TOKEN_EXPIRATION")
        val authTokenTypeKey = stringPreferencesKey("AUTH_TOKEN_TYPE")
    }
}

